<template>
	<el-select
		:value="value"
		placeholder="请选择年份"
		:multiple="multiple"
		@change="change"
	>
		<el-option
			v-for="item in endOptions"
			:key="item.projectyearId"
			:label="item.projectyearYear"
			:value="item.projectyearId"
			:disabled="item.disabled"
		/>
	</el-select>
</template>

<script>
	import bdApi from "@rc/apis/bd/index.mjs";

	export default {
		props: {
			// 年份id,支持v-model
			value: {
				type: [String, Array],
				default: ""
			},
			// 选择的年份名称,支持.sync
			year: {
				type: String,
				default: ""
			},
			// 完整的选中列表，元素应是包含{projectyearYear,projectyearId}的一个对象，如果选中的对象在可选列表中找不到，则会作为一个禁用选项插入到可选列表中用于回显
			checkFullList: {
				type: Array,
				default: () => []
			},
			// 是否多选
			multiple: {
				type: Boolean,
				default: false
			},
			// 项目id
			projectId: {
				type: String,
				default: ""
			},
			// 项目id是否需要必传
			isProjectRequired: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				options: [] // 从后端获取的合法选项列表
			};
		},
		computed: {
			endOptions() {
				let noneItems = this.checkFullList.filter((i1) => {
					// 判断条件这么多主要是兼容多选和单选
					return (
						(this.value || this.value.length) &&
						(i1.projectyearId === this.value || this.value.some((i) => i === i1.projectyearId)) &&
						!this.options.some((i2) => i2.projectyearId === i1.projectyearId)
					);
				});
				noneItems = noneItems.map((i) => ({ ...i, disabled: true }));
				return [...noneItems, ...this.options];
			}
		},
		watch: {
			projectId: {
				handler(val) {
					if (!val && this.isProjectRequired) {
						this.options = [];
						return;
					}
					this.queryList(val);
				},
				immediate: true
			}
		},
		methods: {
			queryList(projectId) {
				bdApi.queryProjectYearList({
					data: {
						projectId,
						projectyearAvlstatus: "Y",
						pageIndex: 0, // 分页数据别删，否则数据可能异常
						pageSize: 100
					},
					success: ({ data }) => {
						this.options = data.sort((a, b) => b.projectyearYear - a.projectyearYear);
						this.$emit("ready", this.options);
					}
				});
			},
			change(data) {
				this.$emit("input", data);
				this.$emit("change", data);
				this.$emit("update:year", this.endOptions.find((i) => i.projectyearId === data).projectyearYear);
			},
			api_getOptions() {
				return this.options;
			}
		}
	};
</script>
